<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import ProductPanel from '@/pages/index/components/ProductPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { HawGuessInstance } from '@/types/component'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { useGuessList } from '@/hooks/useGuessList'

const bannerList = ref<BannerItem[]>([])
const getHomeBanner = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

const categoryList = ref<CategoryItem[]>([])
const getHomeCategory = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

const hotList = ref<HotItem[]>([])
const getHomeHot = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot()])
  isLoading.value = false
})

// 加载更多
const { guessRef, onScrolltolower } = useGuessList()
// 下拉刷新
const isTriggered = ref(false)
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置数据
  guessRef.value?.resetData()
  await Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot(), guessRef.value?.getMore()])
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <CustomNavbar />
  <scroll-view
    clas="scroll-view"
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrolltolower"
    scroll-y
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <HawSwiper :list="bannerList" />
      <ProductPanel :list="categoryList" />
      <HotPanel :list="hotList" />
      <HawGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f7f7f7;
  .scroll-view {
    flex: 1;
  }
}
</style>
